<?php
/**
 * Created by PhpStorm.
 * User: Daxu
 * Date: 2018/3/29
 * Time: 21:38
 */

namespace App\Http\Controllers\API;


use App\Http\Controllers\Controller;
use App\Http\Resources\JudicialInterpretationResource;
use App\Model\JudicialInterpretation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class JudicialInterpretationController extends Controller
{
    public function index(Request $request)
    {
        $keyword = $request->get('name', '');
        $models = JudicialInterpretation::query()->when($keyword, function ($query) use ($keyword) {
            $query->where('name', 'like', '%' . $keyword . '%');
        })->paginate();
        return JudicialInterpretationResource::collection($models);
    }


    /**
     * 添加实例
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new JudicialInterpretation();
        $model->fill($request->all());
        $model->save();
        return new JudicialInterpretationResource($model);
    }


    /**
     * 修改实例
     * @param $id
     * @param Request $request
     * @return mixed
     */
    public function update($id, Request $request)
    {
        $model = $this->findModel($id);
        $model->fill($request->all());
        $model->save();
        return new JudicialInterpretationResource($model);
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $model->delete();
            return response()->json(['state' => 'success']);
        } catch (\Exception $e) {
            return response()->json(['state' => 'failed', 'message' => $e->getMessage()], 406);
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        $model = $this->findModel($id);
        return new JudicialInterpretationResource($model);
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = JudicialInterpretation::query()->where('id', $id)->first();
        return $model;
    }
    public function input(Request $request){
        $file = $request->file('file');
        $put = Storage::disk('local')->put('xls',$file);
        \Excel::load(storage_path('app'). '/'.$put, function ($reader) {
            $results  = $reader->getSheet(0)->toArray();
            foreach ($results as $key => $items) {
                if ($key == 0) {
                    continue;
                }
                $law =  new JudicialInterpretation();
                $law->name = $items[0];
                $law->content = $items[1];
                $law->save();
            }
        });
        return response('导入成功', 200);
    }

}
